package org.yan.kangaroo.email.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.yan.kangaroo.common.exception.KangarooBaseException;
import org.yan.kangaroo.common.util.IdWorkerUtils;
import org.yan.kangaroo.common.util.JsonUtils;
import org.yan.kangaroo.email.config.EmailConfig;
import org.yan.kangaroo.email.constant.McpEmailResponseCodeEnum;
import org.yan.kangaroo.pojo.email.constant.EmailStatusEnum;
import org.yan.kangaroo.pojo.email.entity.EmailSendRecord;
import org.yan.kangaroo.pojo.email.vo.request.SendEmailRequest;

/**
 * 邮件发送
 *
 * @author wangx
 * @date 11/13/2019 17:37
 */
@Service
@Slf4j
public class EmailSendService {
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private EmailSendRecordService emailSendRecordService;

    @Autowired
    private EmailConfig emailConfig;


    public EmailSendRecord sendEmail(SendEmailRequest request) {
        EmailSendRecord sendRecord = new EmailSendRecord();
        sendRecord.setSendAccountId(request.getSendAccountId());
        sendRecord.setEmailRecordId(IdWorkerUtils.getFlowIdWorkerInstance().nextId());
        sendRecord.setSubject(request.getSubject());
        sendRecord.setContent(request.getContent());
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            messageHelper.setSubject(request.getSubject());
            messageHelper.setText(request.getContent(), true);
            messageHelper.setFrom(emailConfig.getEmail(), emailConfig.getName());
            if (CollectionUtils.isEmpty(request.getAttachmentList())) {
                sendRecord.setHaveAttachment(Boolean.FALSE);
            }
            sendRecord.setTo(JsonUtils.getInstance().toJson(request.getTos()));
            messageHelper.setTo(request.getTos().toArray(new String[0]));
            if (CollectionUtils.isNotEmpty(request.getCcs())) {
                sendRecord.setCc(JsonUtils.getInstance().toJson(request.getCcs()));
                messageHelper.setCc(request.getCcs().toArray(new String[0]));
            } else {
                sendRecord.setCc("");
            }
            sendRecord.setStatus(EmailStatusEnum.READY.getStatus());
            sendRecord.setRemark(request.getRemark() != null ? request.getRemark() : "");
            emailSendRecordService.insert(sendRecord);
            javaMailSender.send(messageHelper.getMimeMessage());
            sendRecord.setStatus(EmailStatusEnum.SENDING.getStatus());
            emailSendRecordService.update(sendRecord);
        } catch (Exception e) {
            log.error("[sendEmail] 邮件发送失败:", e);
            sendRecord.setStatus(EmailStatusEnum.FAIL.getStatus());
            sendRecord.setFailureReason(e.getMessage());
            emailSendRecordService.update(sendRecord);
            throw new KangarooBaseException(McpEmailResponseCodeEnum.SEND_FAIL);
        }
        sendRecord.setStatus(EmailStatusEnum.SUCCESS.getStatus());
        emailSendRecordService.update(sendRecord);
        return sendRecord;
    }


}
